﻿using System;
using Newtonsoft.Json.Linq;
using WeiXin.Tool;
using WeiXin.Base.Card.Message;

namespace WeiXin.Base.Card
{
    /// <summary>
    /// 卡券服务
    /// http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025056&token=&lang=zh_CN
    /// </summary>
    public abstract class CardAction
    {
        /// <summary>
        /// 创建卡券
        /// </summary>
        /// <param name="cardType">卡券类型</param>
        /// <param name="cardInfo">卡券信息</param>
        /// <param name="access_token">接口令牌</param>
        /// <returns></returns>
        public virtual bool Create(CardType cardType, CardInfo cardInfo, string access_token)
        {
            string sPostUrl = "https://api.weixin.qq.com/card/create?access_token=ACCESS_TOKEN";
            //卡券json数据
            string sCardJsonStr = string.Empty, sReturnMessage = string.Empty;
            //获取卡券类型
            string sCardName = Enum.GetName(typeof(CardType), cardType);
            #region 设置卡券数据

            JObject jInput = new JObject();
            JProperty jCard = new JProperty("card");
            JProperty jType = new JProperty("card_type", sCardName.ToUpper());
            JProperty jCardInfo = new JProperty(sCardName.ToLower(), cardInfo);
            jCard.Add(jType);
            jCard.Add(jCardInfo);
            jInput.Add(jCard);
            #endregion
            //转换卡券json数据
            sCardJsonStr = jInput.ToString();
            return Send(sPostUrl, access_token, sCardJsonStr, out sReturnMessage);
        }

        /// <summary>
        /// 买单推送
        /// </summary>
        /// <param name="message">买单推送信息</param>
        /// <returns></returns>
        public virtual bool Pay(PayCellMessage message)
        {
            string sReturnMessage = string.Empty;
            return message.Send(out sReturnMessage);
        }

        /// <summary>
        /// 自助核销
        /// </summary>
        /// <param name="message">核销卡券信息</param>
        /// <returns></returns>
        public virtual bool SelfConsume(SelfConsumeCellMessage message)
        {
            string sReturnMessage = string.Empty;
            return message.Send(out sReturnMessage);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sPostUrl">提交地址</param>
        /// <param name="access_token">令牌</param>
        /// <param name="data">Post数据</param>
        /// <param name="sReturnMessage">返回结果</param>
        /// <returns></returns>
        private bool Send(string sPostUrl, string access_token, string data, out string sReturnMessage)
        {
            sReturnMessage = HttpHelper.Post(string.Format(sPostUrl, access_token), data);
            JObject jResult = JObject.Parse(sReturnMessage);
            return jResult["errcode"].ToString().Equals("0");
        }
    }
}
